package com.neulogistics.contrib.warehouse.api.application.query;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neulogistics.contrib.warehouse.api.application.converter.InventoryPOVMConverter;
import com.neulogistics.contrib.warehouse.api.application.converter.InventoryQueryPOConverter;
import com.neulogistics.contrib.warehouse.api.application.viewmodel.InventoryViewModel;
import com.neulogistics.contrib.warehouse.infrastructure.persistence.orm.po.InventoryPO;
import com.neulogistics.contrib.warehouse.infrastructure.persistence.orm.service.IInventoryPOService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class InventoryQueryService implements IInventoryQueryService {
    @Resource
    IInventoryPOService inventoryPOService;

    @Override
    public List<InventoryViewModel> getInventoryByWarehouseAndGoods(Integer centerWarehouseId, List<Integer> goodsIds) {
        // todo 待用索引优化
        LambdaQueryWrapper<InventoryPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(InventoryPO::getWarehouseId, centerWarehouseId)
                .in(InventoryPO::getGoodsId, goodsIds);
        List<InventoryPO> inventoryPOS = inventoryPOService.list(queryWrapper);
        List<InventoryViewModel> viewModelList = inventoryPOS.stream().map(InventoryPOVMConverter::POToVM).collect(Collectors.toList());

        return viewModelList;
    }

    @Override
    public InventoryViewModel getById(Integer id) {
        InventoryPO inventoryPO = inventoryPOService.getById(id);
        InventoryViewModel inventoryViewModel = InventoryPOVMConverter.POToVM(inventoryPO);
        return inventoryViewModel;
    }

    @Override
    public Page<InventoryViewModel> page(InventoryQuery inventoryQuery) {
        // 取出条件
        InventoryPO inventoryPOQuery = InventoryQueryPOConverter.queryToPO(inventoryQuery);
        long current = inventoryQuery.getPageNum();
        long pageSize = inventoryQuery.getPageSize();

        // 查询
        LambdaQueryWrapper<InventoryPO> queryWrapper = new LambdaQueryWrapper<>(inventoryPOQuery);
        Page<InventoryPO> page = inventoryPOService.page(new Page<>(current, pageSize), queryWrapper);

        // 构造结果
        Page<InventoryViewModel> viewModelPage = new Page<>(current, pageSize);
        List<InventoryViewModel> viewModelList = page.getRecords().stream()
                .map(InventoryPOVMConverter::POToVM).collect(Collectors.toList());
        viewModelPage.setRecords(viewModelList);
        viewModelPage.setTotal(page.getTotal());

        return viewModelPage;
    }
}
